<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/11/24
 * Time: 14:14
 */

namespace common;

use think\Response;

class ApiReturn
{
    /**
     * @param $data
     * @return Response
     */
    public static function data($data)
    {
        return Response::create($data, 'json');
    }

    /**
     * @param null $data
     * @param string $message
     * @param int $code
     * @return Response
     */
    public static function success($data = null, $message = '', $code = 0)
    {
        if (is_array($data) && empty($data)) {
            $data = null;
        }

        return self::data(
            [
                'code' => $code,
                'msg' => $message,
                'data' => $data === null ? null : $data,
            ]
        );
    }

    /**
     * 错误
     * @param string $message
     * @param string $data
     * @param int $code
     * @return Response
     */
    public static function error($message = '', $data = '', $code = 1)
    {
        if (!$message) {
            $message = ApiError::instance()->message();
        }

        $code = ApiError::instance()->code() !== '' ?: $code;

        return self::data(
            [
                'code' => $code,
                'msg' => $message,
                'data' => $data === null ? null : $data,
            ]
        );
    }

    /**
     * 验证错误
     * @param string $message
     * @param string $data
     * @return Response
     */
    public static function validate($message = '', $data = null)
    {
        if (!$message) {
            $message = ApiError::instance()->message();
        }

        return self::data(
            [
                'code' => -10010,
                'msg' => $message,
                'data' => $data === null ? null : $data,
            ]
        );
    }

    /**
     * 异常错误信息
     * @return Response
     */
    public static function exception()
    {
        return self::data(LogicException::instance()->api());
    }

    /**
     * 直接返回code
     * @param $code
     * @return Response
     */
    public static function code($code)
    {
        return self::data(
            [
                'code' => $code,
                'msg' => '',
                'data' => null
            ]
        );
    }

    /**
     * 自动判断是什么信息
     * @param $data
     * @return Response
     */
    public static function auto($data)
    {
        if (false === $data) {

            if (LogicException::instance()->exception()) {
                return self::exception();
            }

            return self::error();
        }

        return self::success($data);
    }
}